﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Windows.Forms;
using System.ComponentModel;
using Home.ArtDB;

namespace Home.ArtDB.WinGui
{
    /// <summary>
    /// 
    /// </summary>
    public class GridComparer : IComparer
    {
        public DataGridViewColumn SortedColumn;
        public ListSortDirection SortedDirection;

        public DataGridViewRow RowX;
        public DataGridViewRow RowY;

        protected object ValueX;
        protected object ValueY;

        protected object TagX;
        protected object TagY;

        /// <summary></summary>
        /// <param name="sortedColumn"></param>
        /// <param name="sortedDirection"></param>
        public GridComparer(DataGridViewColumn sortedColumn, ListSortDirection sortedDirection)
        {
            SetColumn(sortedColumn, sortedDirection);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="columnname"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        protected void InitRowValues(string columnname, object x, object y)
        {
            RowX = (SortedDirection == ListSortDirection.Ascending) ? (DataGridViewRow)x : (DataGridViewRow)y;
            RowY = (SortedDirection == ListSortDirection.Ascending) ? (DataGridViewRow)y : (DataGridViewRow)x;

            ValueX = RowX.Cells[columnname].Value;
            ValueY = RowY.Cells[columnname].Value;

            TagX = RowX.Cells[columnname].Tag;
            TagY = RowY.Cells[columnname].Tag;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sortedColumn"></param>
        /// <param name="sortedDirection"></param>
        public void SetColumn(DataGridViewColumn sortedColumn, ListSortDirection sortedDirection)
        {
            if (sortedColumn != null)
                SortedColumn = sortedColumn;

            SortedDirection = sortedDirection;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public virtual int Compare(object x, object y)
        {
            InitRowValues(SortedColumn.Name, x, y);

            switch (SortedColumn.Name)
            {
                case ArtFile.TRACK:
                    return (int)(Convert.ToDouble(ValueX) - Convert.ToDouble(ValueY));

                default:
                    return String.Compare(ValueX.ToString(), ValueY.ToString());
            }
        }
    }
}
